package com.inforich.building.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inforich.building.domain.BuildingType;
import com.inforich.building.mapper.BuildingTypeMapper;
import com.inforich.building.service.IBuildingTypeService;
import com.inforich.common.core.domain.TreeSelect;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;

/**
 * 建筑物类型Service业务层处理
 *
 * @author hjm
 * @date 2022-10-22
 */
@Service
public class BuildingTypeServiceImpl extends
    ServiceImpl<BuildingTypeMapper, BuildingType> implements IBuildingTypeService {

  @Override
  public Page<BuildingType> pageBuildingType(Page<BuildingType> page, Map<String, Object> map) {
    return baseMapper.pageBuildingType(page, map);
  }

  @Override
  public List<BuildingType> listBuildingType(Map<String, Object> map) {
    return baseMapper.listBuildingType(map);
  }

  @Override
  public List<TreeSelect> selectBuildingTypeTreeList(List<BuildingType> list) {
    // 父节点
    List<BuildingType> parentList = list.stream().filter(l -> l.getParentId() == null)
        .collect(Collectors.toList());
    // 父节点树
    List<TreeSelect> tree = convert(parentList);
    // 根据父类型分组
    Map<Long, List<BuildingType>> map = list.stream()
        .filter(b -> b.getParentId() != null)
        .collect(Collectors.groupingBy(BuildingType::getParentId));
    recursionFn(tree, map);
    return tree;
  }

  /**
   * 对象->树对象
   */
  private List<TreeSelect> convert(List<BuildingType> list) {
    return list.stream().map(l -> {
      TreeSelect t = new TreeSelect();
      t.setId(l.getId());
      t.setLabel(l.getName());
      return t;
    }).collect(Collectors.toList());
  }

  /**
   * 递归列表
   */
  private void recursionFn(List<TreeSelect> tree, Map<Long, List<BuildingType>> map) {
    tree.forEach(t -> {
      List<BuildingType> children = map.get(t.getId());
      if (CollUtil.isNotEmpty(children)) {
        List<TreeSelect> treeChildren = convert(children);
        t.setChildren(treeChildren);
        recursionFn(treeChildren, map);
      }
    });
  }

}
